package com.xbj.cloud.voaMeeting.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.MutablePair;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: 辛之所想
 * @create: 2025-06-05 15:25
 * @description: 获取配置参数工具类
 **/
@Component
public class GetConfigParameterUtil {
    private final static ConcurrentHashMap<String, MutablePair<String, Date>> parameterMap = new ConcurrentHashMap<>(30);
    private static Properties properties;
   /**
    * @Author 辛之所想
    * @Date  2025/6/5
    * @Param
    * @Description 获取configParameter.properties中配置的参数
    **/
    static {
        try {
            properties = new Properties();
            properties = PropertiesLoaderUtils.loadAllProperties("configParameter.properties");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Author 辛之所想
     * @Date  2025/6/5
     * @Param
     * @Description 根据参数名获取值, 若配置文件中没有该参数值则查询缓存中是否有值,若有且未过期则返回其值;若无或已过期则查询数据库中是否有值,若数据库中有值,则更新缓存,并返回该值;
     **/
    public static String getValue(String parameterName){
        //先从配置文件中获取值
        String value = properties.getProperty(parameterName);
        if(StringUtils.isBlank(value)){
            //若配置文件中没有该参数值则查询缓存中是否有值
            MutablePair<String, Date> pair = parameterMap.get(parameterName);
            int cacheTime = Integer.parseInt(properties.getProperty("configParameter.cache.time"));
            if(pair!=null && new Date().getTime() - pair.getValue().getTime() < cacheTime*1000 ){
                value = pair.getKey();
            }else {
//                // 若缓存中无值或已过期,则查询数据库
//                String svcName = parameterName;
//                value = constantDao.searchValue(svcName);
//                parameterMap.put(parameterName, MutablePair.of(value, new Date()));
            }
        }
        return value;
    }

}
